<template>
  <div class="realm">
    <div class="realm-header">
      <img :src="spu?.spu_img_list?.[0]?.img" :alt="spu?.title" class="realm-image" />
      <div class="realm-info">
        <div class="realm-title">{{ spu?.title }}</div>
        <div class="realm-price">¥{{ formatPrice(selectedSku?.price || spu?.price) }}</div>
      </div>
      <van-icon name="cross" @click="$emit('close')" />
    </div>

    <div class="realm-content">
      <!-- SKU选择 -->
      <div v-if="spu?.sku_list?.length > 1" class="sku-options">
        <div v-for="spec in spuSpecs" :key="spec.key" class="spec-group">
          <div class="spec-title">{{ spec.key }}</div>
          <div class="spec-values">
            <van-button 
              v-for="value in spec.values" 
              :key="value"
              :type="selectedSpecs[spec.key] === value ? 'primary' : 'default'"
              size="small"
              @click="selectSpec(spec.key, value)"
            >
              {{ value }}
            </van-button>
          </div>
        </div>
      </div>

      <!-- 数量选择 -->
      <div class="quantity-selector">
        <div class="quantity-title">数量</div>
        <van-stepper v-model="quantity" min="1" max="99" />
      </div>
    </div>

    <div class="realm-footer">
      <van-button 
        v-if="orderWay === 'cart'" 
        type="warning" 
        size="large" 
        block
        @click="addToCart"
      >
        加入购物车
      </van-button>
      <van-button 
        v-else 
        type="danger" 
        size="large" 
        block
        @click="buyNow"
      >
        立即购买
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { showToast } from 'vant'

const props = defineProps({
  spu: {
    type: Object,
    default: () => ({})
  },
  orderWay: {
    type: String,
    default: 'cart'
  }
})

const emit = defineEmits(['shopping', 'specchange', 'close'])

// 响应式数据
const selectedSpecs = ref({})
const selectedSku = ref(null)
const quantity = ref(1)

// 计算属性
const spuSpecs = computed(() => {
  if (!props.spu?.sku_list?.length) return []
  
  const specs = {}
  props.spu.sku_list.forEach(sku => {
    sku.specs.forEach(spec => {
      if (!specs[spec.key]) {
        specs[spec.key] = new Set()
      }
      specs[spec.key].add(spec.value)
    })
  })
  
  return Object.keys(specs).map(key => ({
    key,
    values: Array.from(specs[key])
  }))
})

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return parseFloat(price).toFixed(2)
}

// 选择规格
const selectSpec = (key, value) => {
  selectedSpecs.value[key] = value
  
  console.log('=== SKU选择调试 ===')
  console.log('选择的规格:', { key, value })
  console.log('当前所有选择:', selectedSpecs.value)
  console.log('可用SKU列表:', props.spu?.sku_list)
  
  // 根据选择的规格找到对应的 SKU
  if (props.spu?.sku_list) {
    const sku = props.spu.sku_list.find(sku => {
      console.log('检查SKU:', sku.id, sku.specs)
      const match = sku.specs.every(spec => {
        const isMatch = selectedSpecs.value[spec.key] === spec.value
        console.log(`  规格匹配检查: ${spec.key}="${spec.value}" vs 选择的="${selectedSpecs.value[spec.key]}" = ${isMatch}`)
        return isMatch
      })
      console.log(`  SKU ${sku.id} 匹配结果:`, match)
      return match
    })
    selectedSku.value = sku
    console.log('最终选择的SKU:', selectedSku.value)
  }
  console.log('==================')
  
  // 触发规格变化事件
  emit('specchange', {
    noSpec: false,
    skuIntact: !!selectedSku.value,
    missingKeys: getMissingKeys(),
    currentValues: getCurrentValues()
  })
}

// 获取缺失的规格
const getMissingKeys = () => {
  const missing = []
  spuSpecs.value.forEach(spec => {
    if (!selectedSpecs.value[spec.key]) {
      missing.push(spec.key)
    }
  })
  return missing.join('、')
}

// 获取当前选择的规格
const getCurrentValues = () => {
  const values = []
  spuSpecs.value.forEach(spec => {
    if (selectedSpecs.value[spec.key]) {
      values.push(`${spec.key}:${selectedSpecs.value[spec.key]}`)
    }
  })
  return values.join('、')
}

// 添加到购物车
const addToCart = () => {
  console.log('=== 添加到购物车调试 ===')
  console.log('selectedSku.value:', selectedSku.value)
  console.log('spu.sku_list.length:', props.spu?.sku_list?.length)
  console.log('需要选择规格?', !selectedSku.value && props.spu?.sku_list?.length > 1)
  console.log('当前选择的规格:', selectedSpecs.value)
  console.log('缺失的规格:', getMissingKeys())
  
  if (!selectedSku.value && props.spu?.sku_list?.length > 1) {
    console.log('显示"请选择规格"提示')
    showToast('请选择规格')
    return
  }
  
  const sku = selectedSku.value || props.spu?.sku_list?.[0]
  console.log('最终使用的SKU:', sku)
  
  if (!sku) {
    console.log('SKU为空，显示商品信息错误')
    showToast('商品信息错误')
    return
  }
  
  console.log('发送shopping事件:', {
    sku,
    skuCount: quantity.value,
    orderWay: 'cart'
  })
  console.log('========================')
  
  emit('shopping', {
    sku,
    skuCount: quantity.value,
    orderWay: 'cart'
  })
}

// 立即购买
const buyNow = () => {
  if (!selectedSku.value && props.spu?.sku_list?.length > 1) {
    showToast('请选择规格')
    return
  }
  
  const sku = selectedSku.value || props.spu?.sku_list?.[0]
  if (!sku) {
    showToast('商品信息错误')
    return
  }
  
  emit('shopping', {
    sku,
    skuCount: quantity.value,
    orderWay: 'buy'
  })
}

// 监听spu变化，初始化规格
watch(() => props.spu, (newSpu) => {
  if (newSpu?.sku_list?.length === 1) {
    // 只有一个SKU，无需选择规格
    selectedSku.value = newSpu.sku_list[0]
    emit('specchange', {
      noSpec: true,
      skuIntact: true,
      missingKeys: '',
      currentValues: ''
    })
  } else {
    // 多个SKU，需要选择规格
    selectedSpecs.value = {}
    selectedSku.value = null
    emit('specchange', {
      noSpec: false,
      skuIntact: false,
      missingKeys: getMissingKeys(),
      currentValues: ''
    })
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.realm {
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
}

.realm-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  
  .realm-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 8px;
    margin-right: 15px;
  }
  
  .realm-info {
    flex: 1;
    
    .realm-title {
      font-size: 16px;
      color: #333;
      margin-bottom: 5px;
    }
    
    .realm-price {
      font-size: 18px;
      font-weight: bold;
      color: #157658;
    }
  }
}

.realm-content {
  .sku-options {
    margin-bottom: 20px;
    
    .spec-group {
      margin-bottom: 15px;
      
      .spec-title {
        font-size: 14px;
        color: #333;
        margin-bottom: 10px;
      }
      
      .spec-values {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
  
  .quantity-selector {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .quantity-title {
      font-size: 14px;
      color: #333;
    }
  }
}

.realm-footer {
  .van-button {
    height: 44px;
  }
}
</style> 